package com.example.myapplication.audio;


import com.example.myapplication.ResourceTable;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.media.common.Source;
import ohos.media.player.Player;

import java.io.*;

/**
 * 音乐：Created by Miaolonglong on 2021/12/23.
 */

public class MyMusic {
	
	private Context mContext;
	private Player mediaPlayer;
	private int mFileName;
		
	public MyMusic(Context mContext) {
		super();
		this.mContext = mContext;
		mediaPlayer = new Player(mContext);
	}

    public void play(int mediaId,boolean looping){
            if(mFileName == mediaId){
                return;
            }else{
                try {
                    mediaPlayer.reset();
                    mFileName = mediaId;
                    //获取音频资源目录
                    String mUrl = mContext.getResourceManager().getMediaPath(mFileName);
                    File file = new File(mUrl); // 根据实际情况设置文件路径
                    FileInputStream in = new FileInputStream(file);
                    FileDescriptor fd = in.getFD(); // 从输入流获取FD对象
                    Source source = new Source(fd);
                    mediaPlayer.setSource(source);
                    mediaPlayer.enableSingleLooping(looping);//单曲循环
                    mediaPlayer.prepare();
                    mediaPlayer.play();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (NotExistException e) {
                    e.printStackTrace();
                } catch (WrongTypeException e) {
                    e.printStackTrace();
                }
            }
    }
	public void stop(){
		if(mediaPlayer.isNowPlaying()){
			mediaPlayer.stop();
		}
	}
	
	public void pause(){
        try {
            if(mediaPlayer.isNowPlaying()){
                mediaPlayer.pause();
            }
        } catch (IllegalStateException e) {
        }
    }



}
